import L from "leaflet";
import "@geoman-io/leaflet-geoman-free";
import "leaflet.vectorgrid"; //引用矢量瓦片插件
let TileLnglatTransform = require("tile-lnglat-transform"); //  用于经纬度转换为瓦片坐标
let x1, y1, x2, y2;
// 根据地图平台使用转换类
let TileLnglatTransformGaode = TileLnglatTransform.TileLnglatTransformGaode;
let tileALL = []; // 保存所有层级瓦片坐标等信息
const httpRequest = "http://localhost:8888";
const api = `${httpRequest}/api/downloadMap`;
initMap();
function initMap() {
  const map = L.map("map", {
    attributionControl: false,
  }).setView([23.56, 113.23], 14);
  L.tileLayer(
     "http://webst0{s}.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
     { subdomains: ["1", "2", "3", "4"], crossOrigin: true }
  ).addTo(map);
  map.pm.addControls({
    position: "topleft",
    drawMarker: false,
    drawCircleMarker: false,
    drawPolyline: false,
    drawRectangle: true,
    drawPolygon: false,
    drawCircle: false,
    drawText: false,
    editMode: false,
    dragMode: false,
    cutPolygon: false,
    removalMode: true,
    rotateMode: false,
  });
  map.pm.setLang("zh");
  map.on("pm:create", (e) => {
    // console.log(e);
    // 左下角
    const southWest = e.layer._bounds._southWest;
    // 右上角
    const northEast = e.layer._bounds._northEast;
    (x1 = southWest.lng), (y1 = northEast.lat); // 起始点坐标（左上角）
    (x2 = northEast.lng), (y2 = southWest.lat); // 终点坐标（右下角）
    tileALL = [];
    const minzoom = Number($("#minZoom").val());
    const maxzoom = Number($("#maxZoom").val());
    for (let i = minzoom; i <= maxzoom; i++) {
      tileALL[i] = {};
      let p1 = TileLnglatTransformGaode.lnglatToTile(x1, y1, i);
      let p2 = TileLnglatTransformGaode.lnglatToTile(x2, y2, i);
      tileALL[i].t = i; // 层级
      tileALL[i].x = [p1.tileX, p2.tileX]; // 瓦片横坐标范围（左至右）
      // tileALL[i].y = [p2.tileY, p1.tileY]; // 瓦片纵坐标范围（下至上）
      tileALL[i].y = [p1.tileY, p2.tileY]; // 瓦片纵坐标范围（下至上）
    }
    // console.log("tileALL:",tileALL);
  });
  $("#downloadMap_Btn").click(function () {
    if (tileALL.length === 0) return;
    const minzoom = Number($("#minZoom").val());
    const maxzoom = Number($("#maxZoom").val());
    $.ajax({
      type: "POST",
      url: api,
      data: {
        tileALL: tileALL,
        minzoom: minzoom,
        maxzoom: maxzoom,
      },
      success: function (res) {
        console.log("res", res);
      },
      error: function (e) {
        console.error("请求接口失败:", e);
      },
    });
  });
}
